<?php
header('Content-Type: application/json');
require('config.php');
require('functions.php');
$act = $_REQUEST['act'];
if($act == 'fblogin'){
	if(isset($_POST['token'])){
		require('facebooksdk/src/facebook.php');

		$facebook = new Facebook($fbconfig);
		$facebook->setAccessToken($_POST['token']);

		$fbData = $facebook->api(_FB_API_VERSION . '/me');
		if(!isset($fbData['id'])){
			echo json_encode(array('error' => 'Could not informations from Facebook'));
			exit(0);
		}
		$fbUserId = $fbData['id'];
		// $fbUserId = $facebook->getUser();
		$userList = getUsersByFb($fbUserId);
		if(!empty($userList)){
			$_SESSION['cs_tmp_token'] = $_POST['token'];
			$totalAccount = sizeof($userList);
			echo json_encode($userList);
		}
		else{
			// new user
			// insert new user to DB
			if(!isset($fbData['username']) || $fbData['username'] == ''){
				$fbData['username'] = 'UNKNOWNUSER_' . $fbUserId;
			}
			if(!isset($fbData['email']) || $fbData['email'] == ''){
				$fbData['email'] = 'UNKNOWNEMAIL_' . $fbUserId;
			}
			if($userId = addUser(array(
				'user_name' => $fbData['username'],
				'user_fb_id' => $fbUserId,
				'user_password' => md5(time()),
				'user_email' => $fbData['email'],
				'user_activate' => 'YES'
			))){
				$userInfo = array(
					'user_id' => $userId,
					'user_name' => $fbData['username'],
					'user_email' => $fbData['email'],
					'user_authorized' => 'NO',
					'user_fb_data' => json_encode($fbData),
					'user_timezone' => '',
					'user_role' => 'USER'
				);
				$pageInfo = getPagesByUser($userId);
				$groupInfo = getGroupsByUser($userId);

				setUserLoginSession($userInfo);
				$_SESSION['cs_user_pages'] = $pageInfo;
				$_SESSION['cs_user_groups'] = $groupInfo;
				echo json_encode(array('fbreg' => 'success'));
			}
			else{
				echo json_encode(array('error' => 'Could not add user to DB'));
				exit(0);
			}
		}
	}
	exit(0);
}
requireAuth();

if($act == 'rss-grabber'){
	$url = $_POST['url'];
	$limit = intval($_POST['limit']);
	if($limit <= 0) $limit = 10;

	$response = rssExtractor($url, $limit);
	echo json_encode($response);
}
elseif($act == 'fbstat'){
	$urls = json_decode(stripslashes($_POST['urls']), true);
	if(!empty($urls)){
		$response = json_decode(getSocialInfo($urls), true);
		if(!empty($response['data'])){
			$arrResponse = array();
			foreach($response['data'] as $res){
				$res['share_count'] = number_format($res['share_count']);
				$res['like_count'] = number_format($res['like_count']);
				$res['comment_count'] = number_format($res['comment_count']);

				$arrResponse[base64_encode($res['url'])] = $res;
			}
			echo json_encode($arrResponse);
		}
		else{
			echo json_encode(array('error' => 1, 'msg' => 'Error when getting facebook data'));
		}
	}
	else{
		echo json_encode(array('error' => 1, 'msg' => 'Error when getting facebook data'));
	}
}
elseif($act == 'delete-user'){
	$uid = intval($_POST['uid']);
	if(isAdmin()){
		if(deleteUser($uid)){
			echo json_encode(array('success' => 1));
		}
		else{
			echo json_encode(array('error' => 1, 'msg' => 'Error when deleting user'));
		}
	}
	else{
		echo json_encode(array('error' => 1, 'msg' => 'You are not an Administrator'));
	}
}

elseif($act == 'save-template'){
	requireAuth();

	$msgs = $_POST['msg'];
	$urls = $_POST['url'];

	$rawPic = isset($_POST['picture']) ? $_POST['picture'] : null;
	$rawCaption = isset($_POST['caption']) ? $_POST['caption'] : null;
	$rawDesc = isset($_POST['desc']) ? $_POST['desc'] : null;

	$picture = addslashes(json_encode(explode("\n", $rawPic)));
	$caption = addslashes(json_encode(explode("\n", $rawCaption)));
	$desc = addslashes(json_encode(explode("\n", $rawDesc)));

	$targets = addslashes(json_encode($_POST['targets']));
	$interval = isset($_POST['interval']) ? intval($_POST['interval']) : null;

	$arrUrl = addslashes(json_encode(explode("\n", $urls)));
	$arrMsg = addslashes(json_encode(explode("\n", $msgs)));
	$from = isset($_POST['from']) ? cleanValue($_POST['from']) : null;
	$name = isset($_POST['name']) ? cleanValue($_POST['name']) : null;
	
	$arrFrom = array('SINGLEPAGE','BULKPAGE','SINGLEGROUP','BULKGROUP');
	if(!in_array($from, $arrFrom)) $from = 'SINGLEPAGE';

	$params = array(
		's_post_from'	=> $from,
		's_user_id'	=> $userId,
		's_name'	=> $name,
		's_post_url'	=> $arrUrl,
		's_post_message'	=> $arrMsg,
		's_post_picture'	=> $picture,
		's_post_caption'	=> $caption,
		's_post_desc'	=> $desc,
		's_interval'	=> $interval,
		's_post_created_at'	=> date('Y-m-d H:i:s'),
		's_target'	=> $targets
		);
	$result = null;
	if(saveTemplate($params)){
		$result = 1;
	}
	else{
		$result = mysql_error();
	}
	echo json_encode(array('result' => $result));
}

elseif($act == 'load-template'){
	requireAuth();
	$from = cleanValue($_POST['from']);
	$tid = isset($_POST['tid']) ? intval($_POST['tid']) : null;

	$arrFrom = array('SINGLEPAGE','BULKPAGE','SINGLEGROUP','BULKGROUP');
	if(in_array($from, $arrFrom)){
		$result = loadTemplate($from, $tid);
	}
	echo json_encode(array('result' => $result));
}
elseif($act == 'delete-template'){
	requireAuth();
	$tid = isset($_POST['tid']) ? intval($_POST['tid']) : null;
	$result = deleteTemplate($tid);
	echo json_encode(array('result' => $result));
}